
package com.scs.application.modules.settlement.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.settlement.consts.DictConsts;
import com.scs.application.modules.settlement.dto.InvoiceItemDTO;
import com.scs.application.modules.settlement.entity.BillItem;
import com.scs.application.modules.settlement.entity.InvoiceItem;
import com.scs.application.modules.settlement.entity.InvoiceLine;
import com.scs.application.modules.settlement.mapper.InvoiceItemMapper;
import com.scs.application.modules.settlement.mapper.InvoiceLineMapper;
import com.scs.application.modules.settlement.mapper.InvoiceMapper;
import com.scs.application.modules.settlement.request.BillItemQueryRequest;
import com.scs.application.modules.settlement.request.InvoiceItemQueryRequest;
import com.scs.application.modules.settlement.service.BillItemService;
import com.scs.application.modules.settlement.service.BillService;
import com.scs.application.modules.settlement.service.InvoiceItemService;
import com.scs.application.modules.settlement.vo.BillItemVO;
import com.scs.application.modules.settlement.vo.InvoiceItemVO;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 发票单明细 service 实现
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class InvoiceItemServiceImpl extends BaseServiceImpl<InvoiceItemMapper, InvoiceItem> implements InvoiceItemService {

    private final InvoiceLineMapper invoiceLineMapper;

    private final BillItemService billItemService;

    private final BillService billService;

    private final InvoiceMapper invoiceMapper;

    @Override
    public List<InvoiceItem> list(InvoiceItemQueryRequest request) {
        List<InvoiceItem> list = this.list(Wrappers.<InvoiceItem>query()
                .eq(request.getInvoiceLineId() != null, "invoice_line_id", request.getInvoiceLineId())
                .orderByDesc("gmt_modified")
        );
        return list;
    }

    @Override
    public List<InvoiceItemVO> listForView(InvoiceItemQueryRequest request) {
        return baseMapper.listForView(request);
    }

    /*根据入库单号分组*/
    @Override
    public List<InvoiceItemVO> listForViewByHrpKey(InvoiceItemQueryRequest request) {
        return baseMapper.listForViewByHrpKey(request);
    }

    @Override
    public IPage<InvoiceItem> page(InvoiceItemQueryRequest request) {
        IPage page = this.page(request.getPage(), Wrappers.<InvoiceItem>query()
                .eq(request.getInvoiceLineId() != null, "invoice_line_id", request.getInvoiceLineId())
                .orderByDesc("gmt_modified")
        );
        return page;
    }

    @Override
    public IPage<InvoiceItemVO> pageForRelate(InvoiceItemQueryRequest request) {
        request.setSupplierId(UserUtils.getSupplierId());
        return baseMapper.pageForRelate(request.getPage(), request);
    }

    @Override
    public IPage<InvoiceItemVO> pageForView(InvoiceItemQueryRequest request) {
        return baseMapper.pageForView(request.getPage(), request);
    }

    @Override
    public boolean batchDelete(List<String> ids, String invoiceLineId) {
        InvoiceLine byId = invoiceLineMapper.selectById(invoiceLineId);
        //修改关联记账单数量
        int billQty = byId.getBillQty() - ids.size();
        InvoiceLine invoiceLine = new InvoiceLine();
        invoiceLine.setBillQty(billQty).setId(invoiceLineId);
        invoiceLineMapper.updateById(invoiceLine);
        return removeByIds(ids);
    }

    /**
     * 删除开票单明细
     */
    @Override
    public Double deleteInvoiceItem(InvoiceItemDTO invoiceItemDTO) {
        //通过期号、医院Id、耗材编码、批次、记账单ID、记账单明细状态(未开票)查询所有记账单明细，
        List<BillItemVO> billItemVOS = billItemService.listBillItems(new BillItemQueryRequest().setHospitalId(invoiceItemDTO.getHospitalId())
                .setSupplierId(UserUtils.getSupplierId())
                .setPeriodNo(invoiceItemDTO.getPeriodNo())
                .setMaterialCode(invoiceItemDTO.getMaterialCode())
                .setLot(invoiceItemDTO.getLot())
                .setInvoiceId(invoiceItemDTO.getInvoiceId())
                .setPrice(invoiceItemDTO.getPrice())
                .setDeptName(invoiceItemDTO.getDeptName())
                .setStatus(DictConsts.BILL_ITEM_STATUS_UNINVOICE)
        );
        if (billItemVOS.size() == 0 || billItemVOS == null) {
            throw new BusinessException("未查询到数据");
        }
        List<BillItem> billItems = Lists.newArrayListWithCapacity(billItemVOS.size());
        //修改记账单的开票id为0
        billItemVOS.stream().forEach(m -> {
            BillItem billItem = new BillItem();
            billItem.setInvoiceId("0")
                    .setId(m.getId());
            billItems.add(billItem);
        });
        billItemService.updateBatchById(billItems);
        invoiceMapper.calculatePrice(invoiceItemDTO.getInvoiceId());
        return invoiceMapper.selectById(invoiceItemDTO.getInvoiceId()).getTotalAmount();
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<InvoiceItem> entityList) {

        String invoiceLineId = String.valueOf(entityList.stream().findFirst().get().getInvoiceLineId());
        InvoiceLine byId = invoiceLineMapper.selectById(invoiceLineId);
        int billQty = byId.getBillQty() + entityList.size();
        InvoiceLine invoiceLine = new InvoiceLine();

        //修改关联记账单数量
        invoiceLine.setBillQty(billQty).setId(invoiceLineId);
        invoiceLineMapper.updateById(invoiceLine);
        return super.saveOrUpdateBatch(entityList);
    }

}
